//
//  LoginController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/1/5.
//  Copyright © 2016年 game. All rights reserved.


#import "LoginController.h"
#import "PersonNavView.h"
#import "RegisterController.h"
#import "Manager.h"
#import "ForgetPassController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "ThirSquarView.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import "MyNameChangeCtrl.h"
CG_INLINE void AlertLog (NSString *titleStr,NSString *message,NSString *button1,NSString *button2)
{
    if(!titleStr)
        titleStr = @"";
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: titleStr
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: button1
                                              otherButtonTitles: button2,
                              nil];
    [alertView show];
    
}

@interface LoginController ()<UITextFieldDelegate>
{
    UIView *_textview;
}
@end

@implementation LoginController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.app.myTabBar.tabBar.hidden = YES;
        [self NavView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(242, 242, 242, 1);

    [self CreatTextField];
    [self CrectBnt];
    [self ThirdSquare];
}

#pragma mark--自定义导航
-(void)NavView{

    PersonNavView *naview = [[PersonNavView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    naview.title.text = @"登录";
    naview.BackToFatherView = ^{
        [self GoBackAction];
    };
    [self.view addSubview:naview];
    UIButton *bnt = [UIButton buttonWithType:UIButtonTypeSystem];
    bnt.frame = CGRectMake(W(naview)-60, 20, 60, 44);
    [bnt setTitle:@"注册" forState:UIControlStateNormal];
    [bnt setTitleColor:mainColor forState:UIControlStateNormal];
    [bnt addTarget:self action:@selector(ToRegist) forControlEvents:UIControlEventTouchUpInside];
    [naview addSubview:bnt];
}

-(void)GoBackAction{

    NSArray *viewcontrollers=self.navigationController.viewControllers;
    if (viewcontrollers.count>1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {//push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{//present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}
#pragma mark--注册
-(void)ToRegist{
    RegisterController *regist = [RegisterController new];
    [self.navigationController pushViewController:regist animated:YES];
}
-(void)CreatTextField{
    
    _textview = [self Linview:CGRectMake(-1, 64+44, SCREEN_WIDTH+2, 100) BackgroundColor:[UIColor whiteColor] AddView:self.view];
    _textview.layer.borderWidth = 0.5;
    _textview.layer.borderColor = RGBA(225, 225, 225, 1).CGColor;
    _textview.layer.masksToBounds = YES;
    
    [self Linview:CGRectMake(15, H(_textview)/2, SCREEN_WIDTH-30, 0.5) BackgroundColor:RGBA(225, 225, 225, 1) AddView:_textview];
    
    _userName = [[UITextField alloc]initWithFrame:CGRectMake(50,5, SCREEN_WIDTH-70,H(_textview)/2-10)];
    _userName.placeholder = @"用户名/手机号";
    _userName.tag=1;
    _userName.clearButtonMode = UITextFieldViewModeAlways;
    _userName.returnKeyType = UIReturnKeyDone;
    _userName.delegate = self;
    [_textview addSubview:_userName];
    
    _userPass = [[UITextField alloc]initWithFrame:CGRectMake(X(_userName), H(_textview)/2+5,Width(_userName)-70,H(_textview)/2-10)];
    _userPass.placeholder = @"登录密码";
    _userPass.tag=2;
    _userPass.clearButtonMode = UITextFieldViewModeAlways;
    _userPass.secureTextEntry = YES;
    _userPass.returnKeyType = UIReturnKeyDone;
    _userPass.delegate = self;
    [_textview addSubview:_userPass];
    
    [self CreactImageViewWhithRect:CGRectMake(20, 10, 20, 20) ImageName:@"user" FatherView:_textview];
    [self CreactImageViewWhithRect:CGRectMake(20, Y(_userPass)+10, 20, 20) ImageName:@"password" FatherView:_textview];
    UIButton *eye = [self CreatBntAddView:_textview WhithRect:CGRectMake(W(_textview)-42, Y(_userPass)+10, 20, 20) AndType:UIButtonTypeCustom AndBntImgName:@"eye" AndTitle:@"" Font:0];
    [eye addTarget:self action:@selector(eyeToSee) forControlEvents:UIControlEventTouchUpInside];
}

-(void)eyeToSee{
    _userPass.secureTextEntry = !_userPass.secureTextEntry;
}
-(void)CrectBnt{
    UIButton *login = [self CreatBntAddView:self.view WhithRect:CGRectMake(15, Height(_textview)+20, SCREEN_WIDTH-30, 40) AndType:UIButtonTypeSystem AndBntImgName:@"rew" AndTitle:@"登录" Font:20];
    [login addTarget:self action:@selector(ToLogin:) forControlEvents:UIControlEventTouchUpInside];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    radius(login, 5);
    login.backgroundColor = mainColor;
    [self.view addSubview:login];

    UILabel *label = [self CrectLabelWhithRect:CGRectMake(X(login)+1, Height(login)+10, 100, 20)];
    label.text = @"快捷登录";
    label.textAlignment = NSTextAlignmentLeft;
    label.font = font(12);
    label.textColor = RGBA(69, 69, 69, 1);
    [self.view addSubview:label];
    
    UIButton *forget = [self CreatBntAddView:self.view WhithRect:CGRectMake(SCREEN_WIDTH-88, Height(login)+10, 90, 20) AndType:UIButtonTypeSystem AndBntImgName:@"euiw" AndTitle:@"忘记密码?" Font:12];
    [forget setTitleColor:mainColor forState:UIControlStateNormal];
    [forget addTarget:self action:@selector(forGetPass) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forget];
}
#pragma mark--忘记密码
-(void)forGetPass{
    
    ForgetPassController *forget = [ForgetPassController new];
    [self.navigationController pushViewController:forget animated:NO];
}
#pragma mark--登录接口
-(void)ToLogin:(UIButton *)bnt{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if (_userName.text.length==0||_userPass.text.length==0) {
        [Manager GetHudWhithText:@"账号或密码为空" AndFatherView:self.view];
    }else{
        
        [LoginController LoginRequestWhithUserName:_userName.text UserPass:_userPass.text Result:^(id responseObject, id error) {
            if (!error) {
                [Manager GetHudWhithText:responseObject[@"message"] AndFatherView:self.view];
                NSString *code =responseObject[@"code"];
                if (code.integerValue==200) {
                
                    [self GoBackAction];
                    
                    if (_LoginBolck) {
                        _LoginBolck();
                    }
                }
            }else{
                [Manager GetHudWhithText:@"登录失败请检查您的网络" AndFatherView:self.view];
            }
        }];
    }
}
+(void)LoginRequestWhithUserName:(NSString *)userName UserPass:(NSString *)userPass Result:(LoginResult)LoginResult{

    NSDictionary *dic = @{
                          @"username":[Manager doEncryptStr:userName withKey:EncryKey],
                          @"password":[Manager doEncryptStr:userPass withKey:EncryKey],
                          };

    [[Manager sharedManager]ResponseWhithURL:LoginUrl AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        if (!error) {
            NSString *code =responseObject[@"code"];
            if (code.integerValue==200) {
                
            NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
            [ud removeObjectForKey:@"userName"];
            [ud removeObjectForKey:@"userPass"];
            [ud removeObjectForKey:@"time"];
            
            [ud setObject:userName forKey:@"userName"];
            [ud setObject:userPass forKey:@"userPass"];
            [ud setObject:[NSDate date] forKey:@"time"];
            [ud synchronize];
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            app.isLogin = @"YES";

            }
        }
        
        LoginResult(responseObject,error);
    }];
}

#pragma mark--第三方登录
-(void)ThirdSquare{
    
    ThirSquarView *ThirVIew = [[NSBundle mainBundle]loadNibNamed:@"ThirSquarView" owner:nil options:nil].lastObject;

    ThirVIew.frame = CGRectMake(0, Height(_textview)+100, SCREEN_WIDTH, SCREEN_HEIGHT-(Height(_textview)+100));
    [self.view addSubview:ThirVIew];

    [ThirVIew.qqLonGinBtn addTarget:self action:@selector(QQloginAction) forControlEvents:UIControlEventTouchUpInside];
    [ThirVIew.wChatLoginBtn addTarget:self action:@selector(WechatLogin) forControlEvents:UIControlEventTouchUpInside];
}

-(void)QQloginAction{
    
    if ([QQApiInterface isQQInstalled]) {
        
        [ShareSDK getUserInfo:SSDKPlatformTypeQQ onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
            
            if (state==1) {
                NSDictionary *dic = @{
                                      @"openid":user.uid,
                                      @"username":user.nickname,
                                      @"token":user.credential.token,
                                      };
                [self QQloginWhithDic:dic AndUrl:QQlogin];
            }
        }];

    }else{
        AlertLog(@"", @"没有安装QQ客户端，无法进行QQ登录", @"确定", nil);
    }
}

-(void)QQloginWhithDic:(NSDictionary *)dic AndUrl:(NSString *)url{
    
    [[Manager sharedManager]ResponseWhithURL:url AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
        
        NSLog(@"%@",responseObject);
        
            if (error) {
                [Manager GetHudWhithText:@"登录失败，请检查网络" AndFatherView:self.view];
            }else{
                
                if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
                    
                    NSLog(@"%@",responseObject);
                    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
                    [ud removeObjectForKey:@"userName"];
                    [ud removeObjectForKey:@"userPass"];
                    [ud removeObjectForKey:@"time"];
                    
                    [ud setObject:responseObject[@"data"][@"member"][@"username"] forKey:@"userName"];
                    [ud setObject:[NSDate date] forKey:@"time"];
                    [ud synchronize];
                    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    app.isLogin = @"YES";
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    
                }else if ([responseObject[@"message"]isEqualToString:@"first register"]){
                
                    MyNameChangeCtrl *nameChange = [MyNameChangeCtrl new];
                    nameChange.isAddName = YES;
                    [self.navigationController pushViewController:nameChange animated:YES];
                    
                    nameChange.ChangeBlock = ^(NSString *changName){
                        NSMutableDictionary *tabDic = [NSMutableDictionary dictionary];
                        [tabDic addEntriesFromDictionary:dic];
                        [tabDic setValue:changName forKey:@"username"];
                        [tabDic setValue:@"YES" forKey:@"first"];
                        
                        [self QQloginWhithDic:tabDic AndUrl:url];
                    };

                }else{
                    
                    [Manager GetHudWhithText:responseObject[@"message"] AndFatherView:self.view];
                }
            }
    }];
}

-(void)WechatLogin{
    
    if ([WXApi isWXAppInstalled]) {
        
        [ShareSDK getUserInfo:SSDKPlatformTypeWechat onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
            
            if (state==1) {
                NSDictionary *dic = @{
                                      @"openid":user.uid,
                                      @"username":user.nickname,
                                      @"unionid":user.rawData[@"unionid"],
                                      };
                
                [self QQloginWhithDic:dic AndUrl:Wchatlogin];
            }
            
        }];

    }
    else{
        AlertLog(@"", @"没有安装微信客户端，无法进行微信登录", @"确定", nil);
        
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    return YES;
}
@end
